package life.mahu.community.controller;

import life.mahu.community.dto.CommentDTO;
import life.mahu.community.dto.QuestionDTO;
import life.mahu.community.dto.ResultDTO;
import life.mahu.community.dto.UserQuestionDTO;
import life.mahu.community.enums.CommentTypeEnum;
import life.mahu.community.exception.CustomizeErrorCode;
import life.mahu.community.exception.CustomizeException;
import life.mahu.community.model.Category;
import life.mahu.community.model.User;
import life.mahu.community.model.UserQuestion;
import life.mahu.community.service.CategoryService;
import life.mahu.community.service.CommentService;
import life.mahu.community.service.QuestionService;
import life.mahu.community.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CategoryService categoryService;

    @Resource
    private RedisUtil redis;

    // redis中存储的过期时间s
    private static int ExpireTime = 60*60;

    @GetMapping("/question/{id}")
    public String question(@PathVariable(name = "id") String id, Model model, HttpServletRequest request) {

        // 查询分类
        List<Category> categoryList = categoryService.getList();

        User user = (User) request.getSession().getAttribute("user");

        Long questionId = null;
        try {
            questionId = Long.parseLong(id);
        } catch (NumberFormatException e) {
            throw new CustomizeException(CustomizeErrorCode.INVALID_INPUT);
        }
        QuestionDTO questionDTO = questionService.getById(questionId);
        List<QuestionDTO> relatedQuestions = questionService.selectRelated(questionDTO);
        List<CommentDTO> comments = commentService.listByTargetId(questionId, CommentTypeEnum.QUESTION);

        model.addAttribute("comments", comments);

        if (user != null) {
            //判断用户是否收藏此问题
            List<Long> userQuestionIdList;
            if(redis.hasKey("muhuQuestionUserId="+user.getId())){
                userQuestionIdList = (List<Long>)(List)redis.lGet("muhuQuestionUserId="+user.getId(), 0, -1);
            }else{
                userQuestionIdList = questionService.listByUserID(user.getId());
                if(userQuestionIdList.size() != 0)//不然如果没有收藏的话控制台会报错
                    redis.listRSet("muhuQuestionUserId="+user.getId(), (List<Object>)(List)userQuestionIdList, ExpireTime);
            }
            if (userQuestionIdList.size() != 0 && userQuestionIdList.contains(questionId.intValue())) {
                questionDTO.setLike(true);
            }

            //判断用户是否点赞评论
            List<Long> userCommentIdList;
            if(redis.hasKey("muhuUserId="+user.getId())){
                userCommentIdList = (List<Long>)(List)redis.lGet("muhuUserId="+user.getId(), 0, -1);
            }else{
                userCommentIdList = commentService.listByUserID(user.getId());
                if(userCommentIdList.size() != 0)//不然如果没有收藏的话控制台会报错
                    redis.listRSet("muhuUserId="+user.getId(), (List)userCommentIdList, ExpireTime);
            }
            if(userCommentIdList != null) {
                List<CommentDTO> newComments = new ArrayList<>();
                for (CommentDTO comment : comments) {
                    //一级评论点赞
                    if (comment.getType()==1 && userCommentIdList.contains(comment.getId().intValue())) {
                        comment.setLike(true);
                    }
                    newComments.add(comment);
                }
                model.addAttribute("comments", newComments);
            }
        }
        //累加阅读数
        questionService.incView(questionId);
        model.addAttribute("question", questionDTO);
        model.addAttribute("relatedQuestions", relatedQuestions);
        model.addAttribute("categorys", categoryList);
        return "question";
    }

    /**
     * 收藏
     */
    @ResponseBody
    @RequestMapping(value = "/questionLike", method = RequestMethod.POST)
    public ResultDTO questionLike(@RequestBody UserQuestionDTO userQuestionDTO,
                                  HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }

        UserQuestion userQ = new UserQuestion();
        userQ.setUserId(user.getId());
        userQ.setQuestionId(userQuestionDTO.getQuestionId());
        boolean isTrue = questionService.insertOrUpdateUQ(userQ, userQuestionDTO.getType());
        if(!isTrue){
            ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
        }

        return ResultDTO.okOf();
    }

    @ResponseBody
    @DeleteMapping("/question/{id}")
    public Integer deleteQuestion(@PathVariable("id") Long id){
        return questionService.deleteQuestionById(id);
    }
}
